import { formatTime } from '@/utils/date';
import {
  ArgumentsHost,
  Catch,
  ExceptionFilter,
  HttpException,
  HttpStatus,
} from '@nestjs/common';
import { Request, Response } from 'express';
import { LoggerService } from '@/common/logger/logger.service';
import { getClientIp } from '@/utils/request.info';
import { ResultCodeEnum } from '../enums/resultCode.enum';

@Catch(HttpException)
export class HttpExceptionFilter<T> implements ExceptionFilter {
  constructor(private readonly logger: LoggerService) { }
  catch(exception: HttpException, host: ArgumentsHost) {
    const ctx = host.switchToHttp();
    const request = ctx.getRequest<Request>();
    const response = ctx.getResponse<Response>();


    const message = (exception.getResponse() as any).message instanceof Array
      ? (exception.getResponse() as any).message.join(",")
      : (exception.getResponse() as any)?.message
      || "服务器错误，请稍后重试。";

    const httpStatus =
      exception.getStatus() || HttpStatus.INTERNAL_SERVER_ERROR;

    const responseBody = {
      code: ResultCodeEnum.ERROR,
      httpStatus,
      message,
      path: request.url,
      timestamp: formatTime(new Date()),
    };
    // 记录日志
    this.logger.error({
      ...responseBody,
      ip: getClientIp(request)
    }, exception?.stack || null, 'HttpException')


    if (
      ["jwt expired", "TokenExpiredError: jwt expired", "JsonWebTokenError: invalid signature"].includes(responseBody.message)
    ) {
      responseBody.message = "登录已过期，请重新登录";
    } else if (responseBody.message == "Error: No auth token") {
      responseBody.message = "请先登录";
    } else if (httpStatus == 429) {
      responseBody.message = "请求过于频繁，请稍后再试";
    }

    response.status(httpStatus).json(responseBody);
  }
}
